import request from '@/api/request'

/**
 * 上传图片
 * @param {*} image-base64
 * @returns
 */
export function uploadFile(base64) {
  let formData = new FormData()
  formData.append('file', dataURLtoBlob(base64), new Date().getTime())
  return request({
    url: '/emrweb/file/upload',
    method: 'post',
    processData: false,
    data: formData,
  })
}
/**
 * 上传图片
 * @param {*} image-base64
 * @returns
 */
export function uploadFileWithFile(file) {
  let formData = new FormData()
  formData.append('file', file, new Date().getTime())
  return request({
    url: '/emrweb/file/upload',
    method: 'post',
    processData: false,
    data: formData,
  })
}
export function uploadXlS(base64, type, fileName) {
  let formData = new FormData()
  // TODO 可以对fileName做一个后缀名的检测
  formData.append('file', dataURLtoBlob(base64), fileName)
  formData.append('type', type)
  return request({
    url: '/emrweb/file/resolve',
    method: 'post',
    processData: false,
    data: formData,
  })
}
function dataURLtoBlob(base64) {
  const base64Part = base64.split(',')
  let data = atob(base64Part[1])
  let mime = base64Part[0].match(/:(.*?);/)[1]
  let bytes = new ArrayBuffer(data.length)
  let arr = new Uint8Array(bytes)
  for (let i = 0; i < data.length; i++) {
    arr[i] = data.charCodeAt(i)
  }
  return new Blob([arr], { type: mime })
  // var arr = base64.split(','),
  //   mime = arr[0].match(/:(.*?);/)[1],
  //   bstr = atob(arr[1]),
  //   n = bstr.length,
  //   u8arr = new Uint8Array(n)
  // while (n--) {
  //   u8arr[n] = bstr.charCodeAt(n)
  // }
  // return new Blob([u8arr], {
  //   type: mime,
  // })
}
